#!/usr/bin/env python
# -*- coding: utf-8 -*-
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import scrypt
from Crypto.Util.Padding import pad, unpad
import json
import os

PASSWORD = "u0wqRADaBrKWrtzOyIrMCqu64XvAk1rCoJKG3ZFP7wai"
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) + "/conf"
ENCRYPT_FILE = os.path.join(BASE_DIR, 'spider.json')


# 设置密钥，通常可以通过密码生成密钥（使用scrypt等密钥派生函数）
def derive_key(password, salt):
    return scrypt(password.encode(), salt, key_len=32, N=2 ** 14, r=8, p=1)


# 加密函数
def encrypt_json(data, password):
    # 将 JSON 数据转换为字节格式
    json_data = json.dumps(data).encode()

    # 创建一个随机的盐
    salt = os.urandom(16)

    # 使用密码和盐派生加密密钥
    key = derive_key(password, salt)

    # 创建 AES 加密器，使用 CBC 模式
    cipher = AES.new(key, AES.MODE_CBC)

    # 使用 PKCS7 填充以确保数据块大小符合要求
    ciphertext = cipher.encrypt(pad(json_data, AES.block_size))

    # 返回盐、初始化向量 (IV) 和密文
    return salt + cipher.iv + ciphertext


# 解密函数
def decrypt_json(encrypted_data, password):
    try:
        # 从加密数据中提取盐、IV 和密文
        salt = encrypted_data[:16]
        iv = encrypted_data[16:32]
        ciphertext = encrypted_data[32:]

        # 使用密码和盐派生加密密钥
        key = derive_key(password, salt)

        # 创建 AES 解密器
        cipher = AES.new(key, AES.MODE_CBC, iv=iv)

        # 解密并去除填充
        decrypted_data = unpad(cipher.decrypt(ciphertext), AES.block_size)

        # 将解密后的字节数据转换回 JSON 格式
        return json.loads(decrypted_data)
    except ValueError as e:
        print(f"解密错误: {e}，可能是加密数据损坏或密钥不匹配。")
        return {}


def read_file(file_path):
    with open(file_path, 'rb') as file:
        return file.read()


def write_file(file_path, data):
    with open(file_path, 'wb') as file:
        file.write(data)


def is_encrypted(encrypted):
    try:
        json.loads(encrypted)
        return False
    except ValueError:
        return True


def read_encrypt_json(file_path=ENCRYPT_FILE, password=PASSWORD):
    file_info = read_file(file_path)
    if not is_encrypted(encrypted=file_info):
        print("文件未加密，正在读取...")
        with open(file_path, 'r') as file:
            return json.load(file)
    else:
        print("文件已加密，解密后读取...")
        with open(file_path, 'rb') as file:
            encrypted_data = file.read()
            return decrypt_json(encrypted_data, password)


def write_encrypt_json(file_path=ENCRYPT_FILE, password=PASSWORD, data=None):
    old_data = read_encrypt_json(file_path)
    if data is None:
        data = old_data
    # 遍历 data 中的键值对，更新 old_data
    for key, value in data.items():
        old_data[key] = value
    with open(file_path, 'w') as f:
        json.dump(old_data, f, ensure_ascii=False, indent=4)
    # 进行加密后再次写入
    write_file(file_path, encrypt_json(old_data, PASSWORD))


def write_json(file_path=ENCRYPT_FILE, password=PASSWORD, data=None):
    old_data = read_encrypt_json(file_path)
    if data is None:
        data = old_data
    # 遍历 data 中的键值对，更新 old_data
    for key, value in data.items():
        old_data[key] = value
    with open(file_path, 'w') as f:
        json.dump(old_data, f, ensure_ascii=False, indent=4)


config_info = read_encrypt_json(ENCRYPT_FILE, PASSWORD)
headers = config_info.get('headers', {})
header_url = config_info.get('header_url', '')
page = config_info.get('page', 1)
spider_type = config_info.get('spider_type', 'xpath')
proxy_pools = config_info.get('proxy_pools', {})
product_keywords = config_info.get('product_keywords', '')
log_path = config_info.get("log_path")
log_name = config_info.get("log_name")
log_level = config_info.get("log_level")

# if __name__ == '__main__':
# data = {
#     "page": 2,
# }
#     print(read_encrypt_json(ENCRYPT_FILE, PASSWORD))
#     write_json(data=data)
#     write_encrypt_json(data=data)
#     print(read_encrypt_json(ENCRYPT_FILE, PASSWORD))
